package net.j4love.dubbo.callback.provider;

import net.j4love.dubbo.callback.api.CallbackListener;
import net.j4love.dubbo.callback.api.CallbackService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author He Peng
 * @create 2017-05-28 22:01
 * @update 2017-05-28 22:01
 * @updatedesc : 更新说明
 * @see
 */
public class CallbackServiceImpl implements CallbackService {

    private static final Map<String,CallbackListener>
            CALLBACK_LISTENERS = new ConcurrentHashMap<>();
    private Long callbackDelay = 500L;

    public void init() {
        Thread callbackListener = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    for (Map.Entry<String, CallbackListener> entry :
                            CALLBACK_LISTENERS.entrySet()) {

                        String listenerKey = entry.getKey();
                        try {

                            entry.getValue().changed(listenerKey + " Changed: " +
                                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            CALLBACK_LISTENERS.remove(listenerKey);

                            Thread.sleep(CallbackServiceImpl.this.callbackDelay);
                        } catch (Throwable t) {
                            t.printStackTrace();

                            CALLBACK_LISTENERS.remove(listenerKey);
                        }
                    }
                }
            }
        }, "callback-listener-thread");
        callbackListener.setDaemon(true);
        callbackListener.start();
    }

    @Override
    public void addListener(String key, CallbackListener listener) {
        CALLBACK_LISTENERS.put(key, listener);
    }

    public static Map<String, CallbackListener> getCallbackListeners() {
        return CALLBACK_LISTENERS;
    }

    public Long getCallbackDelay() {
        return callbackDelay;
    }

    public CallbackService setCallbackDelay(Long callbackDelay) {
        this.callbackDelay = callbackDelay;
        return this;
    }
}
